package com.assets.Fragment;

import static androidx.core.content.ContextCompat.getSystemService;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Ip_set.Url;
import com.assets.MainActivity;
import com.assets.Particulars;
import com.assets.R;
import com.assets.bean.InventoryDataBean;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.assets.newNHF.UhfApplication;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Allot;
import com.assets.room.entity.Allotdetail;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Check;
import com.assets.room.entity.CheckData;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Place;
import com.assets.room.entity.Receives;
import com.assets.room.entity.ReceivesDetail;
import com.assets.room.entity.ReceivesReapply;
import com.assets.room.entity.Returns;
import com.assets.room.entity.Scrap;
import com.assets.room.entity.ScrapScrapdetail;
import com.assets.room.entity.Type;
import com.assets.room.entity.User;
import com.assets.room.entity.Worker;
import com.assets.util.FileUtil;
import com.assets.util.MyOkHttp;
import com.assets.util.NetworkUtils;
import com.assets.util.Since_case;
import com.assets.util.SpUtils;
import com.assets.util.TrustAllCerts;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by zq on 2017/1/13.
 */


/**
 * @类名称: Fragment1
 * @java类的作用: 这个是首页的Fragment
 * @作者: 蒋剑华
 * @CreateDate: 2023/11/21
 * @UpdateUser: updater
 * @UpdateDate: 2023/11/21
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */

public class Fragment1 extends Fragment {
    private ProgressBar downloadBar;

    private List<CheckData> checkDataList;
    private List<Check> checkList;

    private List<User> userList;
    private List<Dept> deptList;
    private List<Asset> assetList;
    private List<Receives> receivesList;
    private List<ReceivesDetail> receivesDetailList;
    private List<ReceivesReapply> receivesReapplyList;

    private List<Worker> workerList;

    private List<Returns> returnsList;

    private List<Type> typeList;
    private List<Place> placeList;

    private Dialog dialog;
    private static final String TAG = "jjh";
    private String getVersionUrl = "http://" + Url.IP + "/api/getVersionPDA";
    private String getAPK = Url.http() + Url.IP + "/api/getAPKPDA";
    private String downloadDataUrl = Url.http() + Url.IP + "/api/getAllAssetData";
    private float versionCode = 0;
    private ImageView iv_up;

    private MainActivity mainActivity;
    private TextView all_assets;//总资产
    private float all, in, idle, stock, rest;
    private TextView in_assets, tv_in_assets;//在用资产
    private TextView idle_assets, tv_idle_assets;//闲置资产
    private TextView stock_pending, tv_stock_pending;//待入库
    private String url;
    private SlideSideMenuExampleActivity activity;
    private PieChart mChart;
    private MyDataBase db;
    private InventoryDataBean inventoryDataBean;
//    private List<Asset> assetList;
    private Switch my_switch;

    private Boolean flag;
    private Boolean isFlag;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        mainActivity = (MainActivity) getActivity();
        return inflater.inflate(R.layout.fragment_second1, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = (SlideSideMenuExampleActivity) getActivity();
        url = "http://" + Url.IP + "/api/assetCountQuery";

        init();
        setChart();
        setData();
        getpie();
        load();
        getVersion();
        updateVersion();
    }


    private void init() {
        db = MyDataBase.init(activity);

        TextView title = activity.findViewById(R.id.title_text);
        title.setText("固定资产");


        my_switch = activity.findViewById(R.id.my_switch);
        boolean isSwitch2 = SpUtils.getInstance().getBoolean("isSwitch");
        Log.d(TAG, "isSwitch: " + SpUtils.getInstance().getBoolean("isSwitch"));
        my_switch.setChecked(SpUtils.getInstance().getBoolean("isSwitch") ? true : false);
        iv_up = (ImageView) activity.findViewById(R.id.rfid_set);
        stock_pending = (TextView) getActivity().findViewById(R.id.stock_pending);
        tv_stock_pending = activity.findViewById(R.id.tv_stock_pending);
        all_assets = (TextView) getActivity().findViewById(R.id.all_assets);
        in_assets = (TextView) getActivity().findViewById(R.id.in_assets);
        tv_in_assets = activity.findViewById(R.id.tv_in_assets);
        idle_assets = (TextView) getActivity().findViewById(R.id.idle_assets);
        tv_idle_assets = activity.findViewById(R.id.tv_idle_assets);
        ImageView imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        imageView.setOnClickListener((View.OnClickListener) v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });

        mChart = (PieChart) getActivity().findViewById(R.id.pieChart);
        //iv_up.setVisibility(View.GONE);
//        iv_up.setOnClickListener(v -> {
//            updateVersion();
//            //updateVersion();
//        });



        my_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isCheck) {

                boolean networkAvailable = NetworkUtils.isNetworkAvailable(getContext());

                if (!networkAvailable) {
                    showToast("网络飞走了...");
                    buttonView.setChecked(SpUtils.getInstance().getBoolean("isSwitch"));
                    return;
                }

                if (isCheck) {

                    SpUtils.getInstance().putBoolean("isSwitch", true);

                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    LayoutInflater inflater = LayoutInflater.from(activity);
                    View v = inflater.inflate(R.layout.layout_offline, null);

                    @SuppressLint({"MissingInflatedId", "LocalSuppress"})
                    TextView title = v.findViewById(R.id.download_title);
                    Button btnOk = v.findViewById(R.id.download_btn_ok);
                    Button btnCancel = v.findViewById(R.id.download_btn_cancel);
                    downloadBar = v.findViewById(R.id.download_pb);

                    dialog = builder.create();
                    dialog.show();
                    dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面

                    btnOk.setOnClickListener(dialogBtnOk -> {


                        //点击显示进度条
                        downloadBar.setVisibility(View.VISIBLE);

                        //改变文字状态
                        title.setText("正在下载中...");

                        //隐藏两个按钮
                        btnOk.setVisibility(View.GONE);
                        btnCancel.setVisibility(View.GONE);


                        // TODO: 2023/11/22 下载数据
                        downloadData(downloadDataUrl);


                        //关闭对话框
//                    dialog.dismiss();


                    });

                    btnCancel.setOnClickListener(dialogBtnCancel -> {

                        my_switch.setChecked(false);
                        SpUtils.getInstance().putBoolean("isSwitch", false);
                        //关闭对话框
                        dialog.dismiss();

                    });

                }else {
                    String sendDataUrl = Url.http() + Url.IP + "/api/sendAllAssetData";
                    SpUtils.getInstance().putBoolean("isSwitch", false);


                    activity.showDialog("正在上传");
//                    Toast.makeText(mainActivity, "你好", Toast.LENGTH_SHORT).show();

                    Map<String, String> map = new HashMap<>();
                    List<CheckData> checkData = MyDataBase.init(activity).checkDataDao().getAssetCheckByFlag("1");
                    String checkDataBean = MyOkHttp.getInstance().getGson().toJson(checkData);
                    List<Check> checks = MyDataBase.init(activity).checkDao().getCheckById("1");
                    String checkBean = MyOkHttp.getInstance().getGson().toJson(checks);
                    List<Asset> assetList = MyDataBase.init(activity).assetDao().getAllAssetByStatus("1");
                    String assetBean = MyOkHttp.getInstance().getGson().toJson(assetList);
                    List<Receives> receivesList = MyDataBase.init(activity).receivesDao().getAllReceivesByStatus("1");
                    String receivesBean = MyOkHttp.getInstance().getGson().toJson(receivesList);
                    List<ReceivesDetail> receivesDetailList = MyDataBase.init(activity).receivesDetailDao().getReceivesDetailByFlag("1");
                    String receivesDetailBean = MyOkHttp.getInstance().getGson().toJson(receivesDetailList);
                    List<ReceivesReapply> receivesReapplyList = MyDataBase.init(activity).receivesReapplyDao().getAllById("1");
                    String receivesReapplyBean = MyOkHttp.getInstance().getGson().toJson(receivesReapplyList);
                    List<Returns> returnsList = MyDataBase.init(activity).returnsDao().getAllDataByStatus("1");
                    String returnsBean = MyOkHttp.getInstance().getGson().toJson(returnsList);
                    List<Scrap> scrapsList = MyDataBase.init(activity).scrapService().getAllData();
                    String scrapsBean = MyOkHttp.getInstance().getGson().toJson(scrapsList);
                    List<ScrapScrapdetail> scrapScrapdetailsList = MyDataBase.init(activity).scrapScrapdetailService().getAllData();
                    String scrapScrapdetailsBean = MyOkHttp.getInstance().getGson().toJson(scrapScrapdetailsList);
                    List<Allot> allotList = MyDataBase.init(activity).allotService().getAllData();
                    String allotBean = new Gson().toJson(allotList);
                    List<Allotdetail> allotdetailList = MyDataBase.init(activity).allotdetailService().getAllData();
                    String allotdetailBean = new Gson().toJson(allotdetailList);
                    List<Place> placeList = MyDataBase.init(activity).placeDao().getAllPlace();
                    String placeBean = new Gson().toJson(placeList);


                    map.put("checkDataList", checkDataBean);
                    map.put("checkList", checkBean);
                    map.put("assetList", assetBean);
                    map.put("receivesList", receivesBean);
                    map.put("receivesDetailList",receivesDetailBean);
                    map.put("receivesReapplyList", receivesReapplyBean);
                    map.put("returnsList", returnsBean);
                    map.put("scrapsList", scrapsBean);
                    map.put("scrapsDetailList", scrapScrapdetailsBean);
                    map.put("allotsList", allotBean);
                    map.put("allotsDetailList", allotdetailBean);
                    map.put("placeList", placeBean);


                    Log.d(TAG, "map: " + map);

                    //上传数据
                    MyOkHttp.getInstance().post(sendDataUrl, map, new MyOkHttp.requestMessage() {
                        @Override
                        public void requestFail() {
                            showToast("提交失败");
                            activity.canDialog();
                        }

                        @Override
                        public void requestComplete() {

                        }

                        @Override
                        public void requestSuccess(Response response) throws IOException {
                            activity.canDialog();
                        }
                    });


                    //删除数据
                    MyDataBase.init(activity).checkDao().deleteAllData();
                    MyDataBase.init(activity).checkDataDao().deleteAllData();
                    MyDataBase.init(activity).deptDao().deleteAllData();
                    MyDataBase.init(activity).userDao().deleteAllData();
                    MyDataBase.init(activity).allotService().deteleAllData();
                    MyDataBase.init(activity).allotdetailService().deleteAllData();
                    MyDataBase.init(activity).assetDao().deleteAllData();
                    MyDataBase.init(activity).receivesDao().deleteAllData();
                    MyDataBase.init(activity).receivesReapplyDao().deleteAllData();
                    MyDataBase.init(activity).receivesDetailDao().deleteAllData();
                    MyDataBase.init(activity).returnsDao().deleteAllData();
                    MyDataBase.init(activity).scrapService().deleteAllData();
                    MyDataBase.init(activity).scrapScrapdetailService().deleteAllData();
                    MyDataBase.init(activity).placeDao().deleteAllData();
                    MyDataBase.init(activity).typeDao().deleteAllData();
                    MyDataBase.init(activity).workerService().deleteAllData();





                    showToast("上传成功!");

                    load();

//                    activity.canDialog();
                }

            }
        });
//        iv_up.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View view) {
//
//
//                return false;
//            }
//        });
        in_assets.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), Particulars.class);
            intent.putExtra("state", "1");//在用资产
            startActivity(intent);
        });
        tv_in_assets.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), Particulars.class);
            intent.putExtra("state", "1");
            startActivity(intent);
        });
//        stock_pending.setOnClickListener(v -> {
//            Intent intent = new Intent(activity, Particulars.class);
//            intent.putExtra("state", "2");
//            startActivity(intent);
//        });
//        tv_stock_pending.setOnClickListener(v -> {
//            Intent intent = new Intent(activity, Particulars.class);
//            intent.putExtra("state", "2");
//            startActivity(intent);
//        });
        idle_assets.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), Particulars.class);
            intent.putExtra("state", "3");//闲置资产
            startActivity(intent);
        });
        tv_idle_assets.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), Particulars.class);
            intent.putExtra("state", "3");//闲置资产
            startActivity(intent);
        });
    }

    private void updateProgressBar() {


    }

    private void downloadData(String url) {

        MyOkHttp.getInstance().get(url, new MyOkHttp.requestMessage() {
            private InventoryDataBean inventoryDataBean;


            @Override
            public void requestFail() {
                showToast("连接服务器失败!");
                dialog.dismiss();
            }

            @Override
            public void requestComplete() {

            }

            @Override
            public void requestSuccess(Response response) throws IOException {

                response.header("Content-Type");
//                 String responseData = response.body().string();
                // 使用指定的字符编码解码数据
                String result = response.body().string();

                long length = response.body().contentLength();
                if (!response.isSuccessful()) {
                    showToast("连接服务器失败!");
                } else {

                    Log.d(TAG, "result: " + result);

                    inventoryDataBean = MyOkHttp.getInstance().getGson().fromJson(result, InventoryDataBean.class);

                    Log.d(TAG, "inventoryDataBean: " + inventoryDataBean.toString());



                    insertData(inventoryDataBean);

                }

            }
        });

    }


    private void insertData(InventoryDataBean bean) {


        Log.d(TAG, "getReceivesList: " + bean.getReceivesList().toString() +
                ",getReceivesDetailList: " + bean.getReceivesDetailList().toString() +
                ",getReceivesReapplyList: " + bean.getReceivesReapplyList().toString());
        bean.getReceivesList().toString();
        bean.getReceivesDetailList().toString();
        bean.getReceivesReapplyList().toString();

        if (bean.getWorkerList() == null) {
//            MyDataBase.init(activity).workerService().insert(new Worker());
        }else {
            List<InventoryDataBean.WorkerDTO> workerDTO = bean.getWorkerList();
            workerList = workerDTO.stream().map(beanWorker -> {

//                Long workerId, String name, String sex,
//                        String phone, String birthday, String email,
//                        String post, String dept, String division,
//                        String createtime, String islogin,
//                        String company, String createuser,
//                        String isFlag

                Worker worker = new Worker();

                worker.setWorkerId(beanWorker.getWorkerId());
                worker.setName(beanWorker.getName());
                worker.setSex(beanWorker.getSex());
                worker.setPhone(beanWorker.getPhone());
                worker.setBirthday(beanWorker.getBirthday());
                worker.setEmail(beanWorker.getEmail());
                worker.setCreatetime(beanWorker.getCreatetime());
                worker.setDept(beanWorker.getDept());
                worker.setIslogin(beanWorker.getIslogin());
                worker.setCompany(beanWorker.getCompany());
                worker.setCreateuser(beanWorker.getCreateuser());
                worker.setIsFlag("0");
                worker.setPost(beanWorker.getPost());
                worker.setDivision(beanWorker.getDivision());
                return worker;
            }).collect(Collectors.toList());

            MyDataBase.init(activity).workerService().insert(workerList);

        }

//        if (bean.getReturnsList() == null) {
//            MyDataBase.init(activity).returnsDao().insertAllData(new Returns());
//        }else {
//            List<InventoryDataBean.ReturnsDTO> returnsDTO = bean.getReturnsList();
//            returnsList = returnsDTO.stream().map(bean4 -> {
//
////                Long returnsId, String receivesId,
////                        String assetNumber, String company,
////                        String deptId, String useDept,
////                        String place, String userId,
////                        String rdate, String operator,
////                        String type, String ndept,
////                        String nuser, String ncompany,
////                        String nuseDept, String nplace,
////                        String status, String date
//
//                Returns returns = new Returns();
//
//                returns.setReturnsId(bean4.getReturnsId());
//                returns.setReceivesId(bean4.getReceivesId());
//                returns.setAssetNumber(bean4.getAssetNumber());
//                returns.setCompany(bean4.getCompany());
//                returns.setDeptId(bean4.getDeptId());
//                returns.setUseDept(bean4.getUseDept());
//                returns.setPlace(bean4.getPlace());
//                returns.setUserId(bean4.getUserId());
//                returns.setRdate(bean4.getRdate());
//                returns.setOperator(bean4.getOperator());
//                returns.setType(bean4.getType());
//                returns.setNdept(bean4.getNdept());
//                returns.setNuser(bean4.getNuser());
//                returns.setNplace(bean4.getNplace());
//                returns.setStatus(bean4.getStatus());
//                returns.setDate(bean4.getDate());
//                returns.setIsFlag("0");
//
//                return returns;
//            }).collect(Collectors.toList());
//
//            MyDataBase.init(activity).returnsDao().insertAllData(returnsList);
//        }


        if (bean.getReceivesReapplyList() == null) {
//            MyDataBase.init(activity).receivesReapplyDao().insertReceivesReapply(new ReceivesReapply());
        }else {
            List<InventoryDataBean.ReceivesReapplyDTO> receivesReapplyDTO = bean.getReceivesReapplyList();
            receivesReapplyList = receivesReapplyDTO.stream().map(bean3 -> {
                ReceivesReapply receivesReapply = new ReceivesReapply();
                receivesReapply.setId(bean3.getId());
                receivesReapply.setReceivesId(Long.valueOf(bean3.getReceivesId()));
                receivesReapply.setName(bean3.getName());
                receivesReapply.setNum(bean3.getNum());
                receivesReapply.setIsaudit(bean3.getIsaudit());
                receivesReapply.setUnaudit(bean3.getUnaudit());
                receivesReapply.setUser(bean3.getUser());
                receivesReapply.setPlace(bean3.getPlace());
                receivesReapply.setSum(bean3.getSum());
                receivesReapply.setIsput(bean3.getIsput());
                receivesReapply.setIsFlag("0");
                return receivesReapply;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).receivesReapplyDao().insertReceivesReapply(receivesReapplyList);
        }

//        if (bean.getReceivesDetailList() == null) {
////            MyDataBase.init(activity).receivesDetailDao().insertReceivesDetail(new ReceivesDetail());
//        }else {
//            List<InventoryDataBean.ReceivesDetailDTO> receivesDetailDTO = bean.getReceivesDetailList();
//            receivesDetailList = receivesDetailDTO.stream().map(bean2 -> {
////                Long receivesDetailId, String receivesId, String assetId, String isreturn, String isFlag
//                ReceivesDetail receivesDetail = new ReceivesDetail();
//
//                receivesDetail.setReceivesDetailId(Long.valueOf(bean2.getReceivesDetailId()));
//                receivesDetail.setReceivesId(bean2.getReceivesId());
//                receivesDetail.setAssetId(bean2.getAssetId());
//                receivesDetail.setIsreturn(bean2.getIsreturn());
//                receivesDetail.setIsFlag("0");
//
//                return receivesDetail;
//            }).collect(Collectors.toList());
//            MyDataBase.init(activity).receivesDetailDao().insertReceivesDetail(receivesDetailList);
//        }


        if (bean.getReceivesList() == null) {
//            MyDataBase.init(activity).receivesDao().insertReceive(new Receives());
        }else {
            List<InventoryDataBean.ReceivesListDTO> receivesDTO = bean.getReceivesList();
            receivesList = receivesDTO.stream().map(receivesBean -> {
                Receives receives = new Receives();
                receives.setReceivesId(Long.valueOf(receivesBean.getReceivesId()));
                receives.setReceivesDept(receivesBean.getReceivesDept());
                receives.setReceivesUser(receivesBean.getReceivesUser());
                receives.setReapplyDate(receivesBean.getReapplyDate());
                receives.setReceivesRemark(receivesBean.getReceivesRemark());
                receives.setStatus(receivesBean.getStatus());
                receives.setReceivesDate(receivesBean.getReceivesDate());
                receives.setIsreturn(receivesBean.getIsreturn());
                receives.setText(receivesBean.getText());
                receives.setPlace(receivesBean.getPlace());
                receives.setCompany(receivesBean.getCompany());
                receives.setDivision(receivesBean.getDivision());
                receives.setCreateuser(receivesBean.getCreateuser());
                receives.setIsFlag("0");

                return receives;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).receivesDao().insertReceive(receivesList);
        }


        List<InventoryDataBean.AssetListDTO> assetDTO = bean.getAssetList();
        if (assetDTO.size() == 0) {
            MyDataBase.init(activity).assetDao().insertAsset(new Asset());
        }else {
            assetList = assetDTO.stream().map(assetListDTO -> {
                Asset asset = new Asset();
                asset.setAssetId(assetListDTO.getAssetId().equals("") ? 0 : Long.valueOf(assetListDTO.getAssetId()));
                asset.setAssetNumber(assetListDTO.getAssetNumber());
                asset.setUserId(assetListDTO.getUserId());
                asset.setDeptId(assetListDTO.getDeptId());
                asset.setAssetName(assetListDTO.getAssetName());
                asset.setModel(assetListDTO.getModel());
                asset.setType(assetListDTO.getType());
                asset.setStatus(assetListDTO.getStatus());
                asset.setGrundlagen(assetListDTO.getGrundlagen());
                asset.setUnit(assetListDTO.getUnit());
                asset.setAmount("".equals(assetListDTO.getAmount()) ? 0L : Double.valueOf(assetListDTO.getAmount()));
                asset.setCreatedate(assetListDTO.getCreatedate());
                asset.setRemark(assetListDTO.getRemark());
                asset.setPlace(assetListDTO.getPlace());
                asset.setImage(assetListDTO.getImage());
                asset.setYear("".equals(assetListDTO.getYear()) ? 0L : Double.valueOf(assetListDTO.getYear()));
                asset.setSalvage("".equals(assetListDTO.getSalvage()) ? 0L : Double.valueOf(assetListDTO.getSalvage()));
                asset.setRfid(assetListDTO.getRfid());
                asset.setReceivesdate(assetListDTO.getReceivesdate());
                asset.setReceiver(assetListDTO.getReceiver());
                asset.setTeam(assetListDTO.getTeam());
                asset.setCompany(assetListDTO.getCompany());
                asset.setUserDept(assetListDTO.getUserDept());
                asset.setDivision(assetListDTO.getDivision());
                asset.setArea(assetListDTO.getArea());
                asset.setAdmin(assetListDTO.getAdmin());
                asset.setSource(assetListDTO.getSource());
                asset.setSupplier(assetListDTO.getSupplier());
                asset.setUsedate(assetListDTO.getUsedate());
                asset.setFinancialCode(assetListDTO.getFinancialCode());
                asset.setCreateUser(assetListDTO.getCreateUser());
                asset.setBrand(assetListDTO.getBrand());
                asset.setAduit(assetListDTO.getAduit());
                asset.setIsPrint(assetListDTO.getIsPrint());
                asset.setAreavalue("".equals(assetListDTO.getAreavalue()) ? 0L : Double.valueOf(assetListDTO.getAreavalue()));
                asset.setAccountant(assetListDTO.getAccountant());
                asset.setTypex(assetListDTO.getTypex());
                asset.setAaa("");
                asset.setIsFlag("0");
                return asset;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).assetDao().insertAsset(assetList);
        }



        List<InventoryDataBean.DeptListDTO> deptDTO = bean.getDeptList();
        if (deptDTO.size() == 0){

        }else {
            deptList = deptDTO.stream().map(data -> {

                Dept dept = new Dept();
                dept.setDeptId("".equals(data.getDeptId()) ? 0L : Long.valueOf(data.getDeptId()));
                dept.setPid("".equals(data.getPid()) ? 0L : Long.valueOf(data.getPid()));
                dept.setPids(data.getPids());
                dept.setSimpleName(data.getSimpleName());
                dept.setFullName(data.getFullName());
                dept.setDescription(data.getDescription());
                dept.setVersion(0);
                dept.setSort("".equals(data.getSort()) ? 0 : Integer.parseInt(data.getSort()));
                dept.setCreateTime(data.getCreateTime());
                dept.setUpdateTime(data.getUpdateTime());
                dept.setCreateUser("".equals(data.getCreateUser()) ? 0L : Long.valueOf(data.getCreateUser()));
                dept.setUpdateUser("".equals(data.getUpdateUser()) ? 0L : Long.valueOf(data.getUpdateUser()));
                dept.setIsFlag("0");
                return dept;
            }).collect(Collectors.toList());
        }


        List<InventoryDataBean.UserListDTO> userDTO = bean.getUserList();
        if (userDTO.size() == 0) {

        }else {
            userList = userDTO.stream().map(bean2 -> {
                User user = new User();
                user.setUserId("".equals(bean2.getUserId()) ? 0L : Long.valueOf(bean2.getUserId()));
                user.setAvatar(bean2.getAvatar());
                user.setAccount(bean2.getAccount());
                user.setPassword(bean2.getPassword());
                user.setSalt(bean2.getSalt());
                user.setName(bean2.getName());
                user.setBirthday(bean2.getBirthday());
                user.setSex(bean2.getSex());
                user.setEmail(bean2.getEmail());
                user.setPhone(bean2.getPhone());
                user.setRoleId(bean2.getRoleId());
                user.setCreateTime(bean2.getCreateTime());
                user.setCreateUser("".equals(bean2.getCreateUser()) ? 0L : Long.valueOf(bean2.getCreateUser()));
                user.setUpdateTime(bean2.getUpdateTime());
                user.setUpdateUser("".equals(bean2.getUpdateUser()) ? 0L : Long.valueOf(bean2.getUpdateUser()));
                user.setVersion(0);
                user.setDeptId(bean2.getDeptId() == null || bean2.getDeptId().isEmpty() ? 0 : Long.valueOf(bean2.getDeptId()));
                user.setData(bean2.getData());
                user.setIsFlag("0");


                return user;
            }).collect(Collectors.toList());

        }


        if (bean.getCheckList() == null) {
//            MyDataBase.init(activity).checkDao().insertCheck(new Check());
        }else {
            List<InventoryDataBean.CheckListDTO> checkDTO = bean.getCheckList();
            checkList = checkDTO.stream().map(bean3 -> {
                Check check = new Check();


                check.setCheckId(bean3.getCheckId());
                check.setCheckFlag(Long.valueOf(bean3.getCheckFlag()));
                check.setPlanRange(bean3.getPlanRange());
                check.setConcreteRange(bean3.getConcreteRange());
                check.setCheckDate(bean3.getCheckDate());
                check.setStatus(bean3.getStatus());
                check.setCreateUser(bean3.getCreateUser());
                check.setCreateDate(bean3.getCreateDate());
                check.setRemark(bean3.getRemark());
                check.setFlag("0");

                return check;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).checkDao().insertCheck(checkList);
        }



        if (bean.getCheckDataList() == null) {
//            MyDataBase.init(activity).checkDataDao().insertCheckData(new CheckData());
        }else {
            List<InventoryDataBean.CheckDataListDTO> checkDataDTO = bean.getCheckDataList();
            checkDataList = checkDataDTO.stream().map(bean4 -> {
                CheckData checkData = new CheckData();
                checkData.setCheckDataId(bean4.getCheckDataId());
                checkData.setCheckId("".equals(bean4.getCheckId()) ? 0L : Long.valueOf(bean4.getCheckId()));
                checkData.setCheckFlag("".equals(bean4.getCheckFlag()) ? 0L : Long.valueOf(bean4.getCheckFlag()));
                checkData.setAssetNumber(bean4.getAssetNumber());
                checkData.setAssetName(bean4.getAssetName());
                checkData.setModel(bean4.getModel());
                checkData.setType(bean4.getType());
                checkData.setCheckResult(bean4.getCheckResult());
                checkData.setPlace(bean4.getPlace());
                checkData.setFlag("0");
                return checkData;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).checkDataDao().insertCheckData(checkDataList);
        }


        List<InventoryDataBean.PlaceListDTO> placeDTO = bean.getPlaceList();
        if (placeDTO.size() == 0) {

        }else {
            placeList = placeDTO.stream().map(bean4 -> {
                Place place = new Place();
                place.setId(bean4.getId());
                place.setName(bean4.getName());
                place.setBig(bean4.getBig());
                place.setRemark(bean4.getRemark());
                place.setPid(bean4.getPid());
                place.setFlag("0");
                return place;
            }).collect(Collectors.toList());
        }


        List<InventoryDataBean.TypeListDTO> typeDTO = bean.getTypeList();
        if (typeDTO.size() == 0) {

        }else {
            typeList = typeDTO.stream().map(bean5 -> {
                Type type = new Type();
                type.setId(Long.valueOf(bean5.getId()));
                type.setTypenum(bean5.getTypenum());
                type.setName(bean5.getName());
                type.setRemark(bean5.getRemark());
                type.setPid(bean5.getPid());
                type.setFlag("0");

                return type;
            }).collect(Collectors.toList());
        }




        MyDataBase.init(activity).deptDao().insertDept(deptList);
        MyDataBase.init(activity).userDao().insertUser(userList);
        MyDataBase.init(activity).placeDao().insertPlace(placeList);
        MyDataBase.init(activity).typeDao().insertType(typeList);

        dialog.dismiss();

        activity.showToast("拉取成功");

        load();

//        Intent intent = new Intent(mainActivity, Check_choose.class);
//        intent.putExtra("checkId", checkId);
//        intent.putExtra("checkStatus", checkStatus);
//        startActivity(intent);



    }

    private void load() {

        Map<String, Object> map = new HashMap<String, Object>();

        User user = MyDataBase.init(activity).userDao().getUserById(Since_case.getInstance().getUserId())/*userService.getById(userId)*/;

        int unused = MyDataBase.init(activity).assetDao().queryById2("4", "13") == null ? 0 : MyDataBase.init(activity).assetDao().queryById2("4", "13").size();
        int asset = MyDataBase.init(activity).assetDao().getAllData() == null ? 0 : MyDataBase.init(activity).assetDao().getAllData().size();
        int use = MyDataBase.init(activity).assetDao().queryById1("1") == null ? 0 : MyDataBase.init(activity).assetDao().queryById1("1").size();
        int entry = 0;


        if (SpUtils.getInstance().getBoolean("isSwitch")) {
            map.put("asset", asset);
            map.put("unused", unused);
            map.put("use", use);
            map.put("entry", entry);
        }else {
            map.put("asset", 0);
            map.put("unused", 0);
            map.put("use", 0);
            map.put("entry", 0);
        }


        showResponse(new Gson().toJson(map));//解析
        //        new Thread() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient client = new OkHttpClient
//                            .Builder()
//                            .hostnameVerifier(new AllowAllHostnameVerifier())
//                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                            .readTimeout(500, TimeUnit.SECONDS)
//                            .build();
//                    RequestBody requestBody = new FormBody.Builder()
//                            .add("userId", Since_case.getInstance().getUserId())
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(url)
//                            .post(requestBody).build();
//                    LogUtils.d(Since_case.getInstance().getUserId() + url);
//                    Response response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    Log.d("主页的数据渲染", "responseData: " + responseData);
//                    LogUtils.d(responseData);
//                    showResponse(responseData);//解析
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }

    private void showResponse(final String responseData) {
        activity.runOnUiThread(() -> {
            try {
                JSONObject js = new JSONObject(responseData);
                all_assets.setText(js.getString("asset"));
                idle_assets.setText(js.getString("unused"));
                in_assets.setText(js.getString("use"));
                if (SpUtils.getInstance().getBoolean("isSwitch")) {
                    stock_pending.setText(/*js.getString("entry")*/MyDataBase.init(activity).userDao().getUserById(Since_case.getInstance().getUserId()) == null ? "---" : MyDataBase.init(activity).userDao().getUserById(Since_case.getInstance().getUserId()).getName());
                }else {
                    stock_pending.setText("---");
                }

                all = Integer.parseInt(js.getString("asset"));
                idle = Integer.parseInt(js.getString("unused"));
                in = Integer.parseInt(js.getString("use"));
                stock = Integer.parseInt(js.getString("entry"));
                rest = all - idle - in - stock;
                setData();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        });
    }

    private void setChart() {

        mChart.setUsePercentValues(true);            //使用百分比显示
        //设置pieChart图表的描述
        mChart.setExtraOffsets(5, 10, 40, 10);        //设置pieChart图表上下左右的偏移，类似于外边距
        mChart.setDragDecelerationFrictionCoef(0.95f);//设置pieChart图表转动阻力摩擦系数[0,1]
        mChart.setRotationAngle(0);                   //设置pieChart图表起始角度
        mChart.setRotationEnabled(true);              //设置pieChart图表是否可以手动旋转
        mChart.setHighlightPerTapEnabled(true);       //设置piecahrt图表点击Item高亮是否可用
        mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);// 设置pieChart图表展示动画效果

        // 设置 pieChart 图表Item文本属性
        mChart.setDrawEntryLabels(false);              //设置pieChart是否只显示饼图上百分比不显示文字（true：下面属性才有效果）
        mChart.setEntryLabelColor(Color.BLACK);       //设置pieChart图表文本字体颜色
        //设置pieChart图表文本字体样式
        mChart.setEntryLabelTextSize(12f);            //设置pieChart图表文本字体大小

        // 设置 pieChart 内部圆环属性
        mChart.setDrawHoleEnabled(true);              //是否显示PieChart内部圆环(true:下面属性才有意义)
        mChart.setHoleRadius(28f);                    //设置PieChart内部圆的半径(这里设置28.0f)
        mChart.setTransparentCircleRadius(31f);       //设置PieChart内部透明圆的半径(这里设置31.0f)
        mChart.setTransparentCircleColor(Color.BLACK);//设置PieChart内部透明圆与内部圆间距(31f-28f)填充颜色
        mChart.setTransparentCircleAlpha(50);         //设置PieChart内部透明圆与内部圆间距(31f-28f)透明度[0~255]数值越小越透明
        mChart.setHoleColor(Color.WHITE);             //设置PieChart内部圆的颜色
        mChart.setDrawCenterText(true);               //是否绘制PieChart内部中心文本（true：下面属性才有意义）
        //设置PieChart内部圆文字的字体样式
        mChart.setCenterText("资产");                 //设置PieChart内部圆文字的内容
        mChart.setCenterTextSize(10f);                //设置PieChart内部圆文字的大小
        mChart.setCenterTextColor(Color.BLACK);         //设置PieChart内部圆文字的颜色
        Description description = new Description();
        description.setText("");
        mChart.setDescription(description);
    }

    private void setData() {
        ArrayList<PieEntry> pieEntryList = new ArrayList<PieEntry>();
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(Color.parseColor("#3794fc"));
        colors.add(Color.parseColor("#2dbe8d"));
        colors.add(Color.parseColor("#db585c"));
        colors.add(Color.parseColor("#f3ab11"));

        //饼图实体 PieEntry
        if (in > 0) {
            PieEntry CashBalance = new PieEntry(in / all, "在用资产 ");
            pieEntryList.add(CashBalance);
        }
        if (idle > 0) {
            PieEntry ConsumptionBalance = new PieEntry(idle / all, "闲置资产 ");
            pieEntryList.add(ConsumptionBalance);
        }
        if (stock > 0) {
            PieEntry CashBalance1 = new PieEntry(stock / all, "待入库 ");
            pieEntryList.add(CashBalance1);
        }
        if (rest > 0) {
            int j = (int) rest;
            PieEntry CashBalance2 = new PieEntry(rest / all, "其他 ");
            pieEntryList.add(CashBalance2);
        }

        //饼状图数据集 PieDataSet
        PieDataSet pieDataSet = new PieDataSet(pieEntryList, "");
        pieDataSet.setSliceSpace(3f);           //设置饼状Item之间的间隙
        pieDataSet.setSelectionShift(10f);      //设置饼状Item被选中时变化的距离
        pieDataSet.setColors(colors);           //为DataSet中的数据匹配上颜色集(饼图Item颜色)
        //最终数据 PieData
        PieData pieData = new PieData(pieDataSet);
        pieData.setDrawValues(true);            //设置是否显示数据实体(百分比,true:以下属性才有意义)
        pieData.setValueTextColor(Color.DKGRAY);  //设置所有DataSet内数据实体(百分比)的文本颜色
        pieData.setValueTextSize(12);          //设置所有DataSet内数据实体(百分比)的文本字体大小
        pieData.setValueFormatter(new PercentFormatter());//设置所有DataSet内数据实体(百分比)的文本字体格式
        mChart.setData(pieData);
        mChart.highlightValues(null);
        mChart.invalidate();                    //将图表重绘以显示设置的属性和数据
    }

    private void getpie() {
        // 获取pieCahrt图列
        Legend l = mChart.getLegend();
        l.setEnabled(true);                    //是否启用图列(true:下面属性才有意义)
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setForm(Legend.LegendForm.DEFAULT); //设置图例的形状
        l.setFormSize(10);                      //设置图例的大小
        l.setFormToTextSpace(10f);              //设置每个图例实体中标签和形状之间的间距
        l.setDrawInside(false);
        l.setWordWrapEnabled(true);              //设置图列换行(注意使用影响性能,仅适用legend位于图表下面)
        l.setXEntrySpace(10f);                  //设置图例实体之间延X轴的间距(setOrientation = HORIZONTAL有效)
        l.setYEntrySpace(8f);                  //设置图例实体之间延Y轴的间距(setOrientation = VERTICAL 有效)
        l.setYOffset(0f);                      //设置比例块Y轴偏移量
        l.setTextSize(14f);                      //设置图例标签文本的大小
        l.setTextColor(Color.parseColor("#130c0e"));//设置图例标签文本的颜色
    }

    private void getVersion() {
        // 获取当前版本号信息
        PackageInfo packInfo = null;
        try {
            packInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        assert packInfo != null;
        versionCode = packInfo.versionCode;
    }


    /**
     * 检查更新版本
     */
    private void updateVersion() {
        //获取服务器里apk版本号
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
        FormBody body = new FormBody.Builder().build();
        Request request = new Request.Builder().url(getVersionUrl).post(body).build();
        try {
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    showToast("数据获取失败");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        showToast("获取最新版本号失败");
                        return;
                    }
                    InputStream inputStream = response.body().byteStream();
                    //使用IO流读取数据
                    String line = null;
                    StringBuffer sb = new StringBuffer();
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                    inputStream.close();
                    in.close();
                    String versionInfo = sb.toString();
                    if (TextUtils.isEmpty(versionInfo)) {
                        showToast("version文件异常");
                        return;
                    }
                    LogUtils.d(versionInfo);
                    float updateVersion = Float.parseFloat(versionInfo.substring(versionInfo.indexOf(":") + 1));
                    LogUtils.d("现用version: " + versionCode + "--最新版本updateVersion:" + updateVersion);
                    activity.runOnUiThread(() -> {
                        if (updateVersion - versionCode <= 0) {
                            showToast("当前是最新版");
                            return;
                        }
                        AlertDialog builder = new AlertDialog.Builder(getContext())
                                .setTitle("更新提示")
                                .setMessage("有新版本是否更新！")
                                .setNegativeButton("否", (dialog, which) -> {

                                }).setPositiveButton("是", (dialog, which) -> {
                                    downloadAPK();
                                }).create();
                        builder.setCanceledOnTouchOutside(false);
                        builder.show();
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("请求错误 ");
        }
    }


    /**
     * 下载最新版apk
     */
    private void downloadAPK() {
        //弹出进度提示框
        showDialog("下载中");
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
        FormBody body = new FormBody.Builder().build();
        Request request = new Request.Builder().url(getAPK).post(body).addHeader("Accept-Encoding", "identity").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showToast("请检查网络！");
                canDialog();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    canDialog();
                    showToast("下载失败，请重试");
                    LogUtils.d("error");
                    return;
                }
                final InputStream in = response.body().byteStream();
                //保存SD卡
                File path = getContext().getExternalFilesDir("apkData");
                FileUtil.loadFile(in, path, "app.apk", new FileUtil.request() {
                    @Override
                    public void success(final File file) {
                        getActivity().runOnUiThread(() -> {
                            canDialog();
                            // 安装apk
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            Uri data;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
                                // 通过FileProvider创建一个content类型的Uri
                                data = FileProvider.getUriForFile(getContext(), "com.shanXiAssets.provider", file);
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
                            } else {
                                data = Uri.fromFile(file);
                            }
                            intent.setDataAndType(data, "application/vnd.android.package-archive");
                            startActivity(intent);
                        });
                    }

                    @Override
                    public void onFailure() {
                        Log.i("测试", "下载异常！");
                        canDialog();
                    }
                });
            }
        });
    }

    private Toast toast;

    private void showToast(final String msg) {
        getActivity().runOnUiThread(() -> {
            if (toast == null) {
                toast = Toast.makeText(activity, msg, Toast.LENGTH_SHORT);
                toast.show();
            } else {
                toast.setText(msg);
                toast.show();
            }
        });
    }

    private ProgressDialog progressDialog;

    private void showDialog(final String titleString) {
        getActivity().runOnUiThread(() -> {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(getContext());
            }
            progressDialog.setTitle(titleString);
            progressDialog.show();
        });

    }

    private void canDialog() {
        getActivity().runOnUiThread(() -> {
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        });
    }



}
